package com.ruoyi.lvlian.util;

import com.alibaba.excel.converters.Converter;
import com.alibaba.excel.enums.CellDataTypeEnum;
import com.alibaba.excel.metadata.GlobalConfiguration;
import com.alibaba.excel.metadata.data.ReadCellData;
import com.alibaba.excel.metadata.property.ExcelContentProperty;

import java.math.BigDecimal;

public class PercentageStringToIntConverter implements Converter<Integer> {

    @Override
    public Class<Integer> supportJavaTypeKey() {
        return Integer.class;
    }

    @Override
    public CellDataTypeEnum supportExcelTypeKey() {
        return CellDataTypeEnum.STRING;
    }

    @Override
    public Integer convertToJavaData(ReadCellData<?> cellData, ExcelContentProperty contentProperty,
                                     GlobalConfiguration globalConfiguration) throws Exception {

        if(CellDataTypeEnum.NUMBER.equals(cellData.getType() )){
            BigDecimal multipliedValue = cellData.getNumberValue().multiply(BigDecimal.valueOf(100));
            int intValue = multipliedValue.intValue();
            return intValue;
        }
        // 将百分比字符串转换为整数
        String stringValue = cellData.getStringValue();
        if (stringValue != null && stringValue.endsWith("%")) {
            stringValue = stringValue.substring(0, stringValue.length() - 1);
            try {
                return Integer.parseInt(stringValue);
            } catch (NumberFormatException e) {
                // 如果无法解析为整数，可以返回一个默认值或抛出异常
                throw new RuntimeException("Invalid percentage format: " + cellData.getStringValue());
            }
        }
        return 0;
    }


}
